﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using ThangNM_LIB.FUNC;
using System.IO;
using Microsoft.Reporting.WinForms;
using DataAccessObject;

namespace ThangNM_WinSV
{
    partial class Auto_Export_File : ServiceBase
    {
        Timer timerAutoReport;
        public Auto_Export_File()
        {
            //System.Diagnostics.Debugger.Launch();
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                if ((new BaoCaoDAO()).CheckConnect())
                    ErrorLog.WriteToEventLog("Connected", Properties.Settings.Default.Service_Name, EventLogEntryType.Information);
                else
                    ErrorLog.WriteToEventLog("Connect Fail", Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
                timerAutoReport = new Timer();
                timerAutoReport.Interval = Properties.Settings.Default.IntervalAutoReport * 1000;
                timerAutoReport.Elapsed += this.evttimerAutoScan;
                timerAutoReport.Start();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(String.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            }
        }

        public void evttimerAutoScan(object sender, System.Timers.ElapsedEventArgs args)
        {
            //ErrorLog.WriteToEventLog("Begin event", Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            Timer timer = (Timer)sender;
            try
            {
                timer.Stop();
                DataTable dt = (new BaoCaoDAO()).SelectList(true, "0");
                if (dt == null || dt.Rows.Count <= 0)
                    return;

                DataTable dtTemp = dt.Copy();
                String sPath = AppDomain.CurrentDomain.BaseDirectory;
                LocalReport report;
                foreach (DataRow dr in dt.Rows)
                {
                    report = new LocalReport();
                    dtTemp.Clear();
                    dtTemp.Rows.Add(dr.ItemArray);
                    report.ReportPath = sPath + "\\rptDoanhSo.rdlc";
                    report.DataSources.Clear();
                    report.DataSources.Add(new ReportDataSource("dsDoanhSo", dtTemp));
                    Byte[] mybytes = report.Render("PDF");
                    using (FileStream fs = File.Create(sPath + "\\PDF\\" + getFileName(dtTemp.Rows[0]["PK_iRID"]) + ".pdf"))
                    {
                        fs.Write(mybytes, 0, mybytes.Length);
                    }
                    (new BaoCaoDAO()).UpdateSync(Convert.ToInt32(dtTemp.Rows[0]["PK_iRID"]), 1);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(string.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            }
            finally
            {
                timer.Start();
            }
        }

        protected override void OnStop()
        {
            try
            {
                //ErrorLog.WriteToEventLog("Begin stop", Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
                timerAutoReport.Stop();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(string.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            }
        }

        private String getFileName(Object PK_iRID)
        {
            String sRet = "";
            try
            {
                sRet = Convert.ToString(PK_iRID);
                DateTime tTemp = DateTime.ParseExact(sRet.Substring(1), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                switch (sRet.Substring(0, 1))
                {
                    case "1": sRet = "bao_cao_doanh_thu_ngay_" + tTemp.ToString("dd-MM-yyyy"); break;
                    case "2": sRet = "bao_cao_doanh_thu_thang_" + tTemp.ToString("MM-yyyy"); break;
                    case "3": sRet = "bao_cao_doanh_thu_thang_tong_hop_" + tTemp.ToString("MM-yyyy"); break;
                }
            }
            catch (Exception ex)
            {
                sRet = "bao_cao_doanh_thu";
            }
            return sRet;
        }
    }
}
